package com.chinatelecom.ifree.business.configcenter.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinatelecom.ifree.business.configcenter.ZkHelp;
import com.github.zkclient.IZkDataListener;

public class NutcrackerHelper {
	private final static Logger logger = LoggerFactory.getLogger(NutcrackerHelper.class);
	private final static String nutZkPath = "/ifree/nut/path";
	private String nutURL = null;
	private ZkHelp zkHelp = ZkHelp.getInstance();
	private static NutcrackerHelper instance = null;
	private static IZkDataListener listener = null;

	private NutcrackerHelper() {
		// mysql URL
		listener = new IZkDataListener() {
			@Override
			public void handleDataDeleted(String dataPath) throws Exception {
				logger.info("!!! rsVersion node data has been deleted !!!" + dataPath);
			}

			@Override
			public void handleDataChange(String dataPath, byte[] data) throws Exception {
				logger.info("!!! rsVersion node data has been changed !!!" + dataPath);
				String rtdata = null;
				if (data != null && data.length > 0) {
					rtdata = new String(data, "UTF-8");
					nutURL = rtdata;
				}
				logger.info("!!! rsVersion node data has been changed ok !!!" + rtdata);
			}
		};
		// 添加节点监控
		zkHelp.subscribeDataChanges(nutZkPath, listener);
		nutURL = new String(zkHelp.getValue(nutZkPath));
		if (logger.isInfoEnabled())
			logger.info("===================init NutcrackerHelper ok================");
	}

	public static NutcrackerHelper getInstance() {
		if (instance == null) {
			synchronized (NutcrackerHelper.class) {
				instance = new NutcrackerHelper();
			}
		}
		return instance;
	}

	public String getNutURL() {
		return nutURL;
	}

	public void setNutURL(String nutURL) {
		this.nutURL = nutURL;
	}
}
